package com.itheima.reggie.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.UUID;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.path-value}")
    private String pathValue;

    //文件下载
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
/*            //设置传输文件类型
            response.setContentType("image/jpeg");
            //获取输入流写入数据,并根据文件路径写入数据
            FileInputStream fileInputStream = new FileInputStream(new File(pathValue + name));
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            int length = 0;
            byte[] bytes = new byte[1024];
            while ((length = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,length);
                outputStream.flush();
            }
            fileInputStream.close();
            outputStream.close();*/
            //设置传输文件类型
            response.setContentType("image/jpeg");
            //获取输入流写入数据,并根据文件路径写入数据
            FileInputStream fileInputStream = new FileInputStream(new File(pathValue + name));
            //获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            IoUtil.copy(fileInputStream,outputStream);
            fileInputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //文件上传
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) throws IOException {
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //截取文件类型
        String lastFile = originalFilename.substring(originalFilename.lastIndexOf("."));
        //以uuid创建新文件名
        String fileName = UUID.randomUUID().toString() + lastFile;
        //获取文件路径
        File file1 = new File(pathValue);
        //判断是否存在，不存在就创建
        if (!file1.exists()) {
            file1.mkdir();
        }
        File pathFile = new File(pathValue + fileName);
        file.transferTo(pathFile);
        return R.success(fileName);
    }
}
